package com.hyacinth.lotterysystem.common.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

/**
 * @Author: Yun
 * @Date: 2025/6/22
 */
public class JacksonUtil {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

//    static {
//        OBJECT_MAPPER = new ObjectMapper();
//    }

    private JacksonUtil() {
    }

    public static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    private static <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JacksonException.class);
    }

    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return (T) parser.call();
        } catch (Exception ex) {
            if (check.isAssignableFrom(ex.getClass())) {
                throw new JsonParseException(ex);
            } else {
                throw new IllegalStateException(ex);
            }
        }
    }

    /**
     * 序列化
     *
     * @param object
     * @return
     */
    public static String writeValueAsString(Object object) {
        return tryParse(() -> JacksonUtil.getObjectMapper().writeValueAsString(object));
    }

    /**
     * 反序列化
     *
     * @param content
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T readValue(String content, Class<T> valueType) {
        return JacksonUtil.tryParse(() -> JacksonUtil.getObjectMapper().readValue(content, valueType));
    }

    public static <T> T readListValue(String content, Class<?> parameterClasses) {
        JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(List.class, parameterClasses);

        return JacksonUtil.tryParse(() -> JacksonUtil.getObjectMapper().readValue(content, javaType));
    }
}
